package com.robotserver.orders.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jd.open.api.sdk.JdClient;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.entity.ElmOrders;
import com.robotserver.orders.mapper.ElmOrdersMapper;
import com.robotserver.orders.service.ElmOrderSyncService;
import com.robotserver.orders.vo.ElmOrderTimeVO;
import com.robotserver.orders.vo.JdOrderTimeVO;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAlscUnionKbcpxPositiveOrderGetRequest;
import com.taobao.api.response.AlibabaAlscUnionKbcpxPositiveOrderGetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: lucher
 * @Date: 2023/03/16 11:24
 * @Description:
 */
@Service
public class ElmOrderSyncServiceImpl implements ElmOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(ElmOrderSyncServiceImpl.class);
    private static int pagesize = 20;
    private static long type = 4L;            // 按照更新时间来查询

    @Autowired
    private ElmOrdersMapper elmOrdersMapper;

    private int bizStatus(int orderItemStatus){
        // 0已失效，1已下单，2已付款，3售中退，4已收货，5售后退
        switch (orderItemStatus){
            case 0:
                return 2;  //无锡奥
            case 2:
                return 0;
            case 3:
                return 3;
            case 4:
                return 1;
            case 5:
                return 3;
        }
        return 4;
    }

    @Override
    public void threadSyncOrder_byAppKey(List<ElmOrderTimeVO> elmOrderTimeVOList, TaobaoClient client, Integer downType){
        for (ElmOrderTimeVO elmOrderTimeVO:elmOrderTimeVOList){
            syncTimeOrder_byAppKey(elmOrderTimeVO,1,client, downType);
        }
    }

    public void syncTimeOrder_byAppKey(ElmOrderTimeVO elmOrderTimeVO, int pageNo,TaobaoClient client, Integer downType) {
        try {
            AlibabaAlscUnionKbcpxPositiveOrderGetRequest orderReq = new AlibabaAlscUnionKbcpxPositiveOrderGetRequest ();
            orderReq.setBizUnit(2L); //1-CPA 2-CPS
            orderReq.setPageNumber(Long.valueOf(pageNo));
            orderReq.setPageSize(Long.valueOf(pagesize));
            orderReq.setStartDate(elmOrderTimeVO.getBeginTime());
            orderReq.setEndDate(elmOrderTimeVO.getEndTime());
            if(downType != null){
                orderReq.setDateType(Long.valueOf(downType));
            }else{
                orderReq.setDateType(type); //订单更新时间
            }
            AlibabaAlscUnionKbcpxPositiveOrderGetResponse response = client.execute(orderReq);
            if (response!=null){
                List<AlibabaAlscUnionKbcpxPositiveOrderGetResponse.OrderDetailReportDTO> result = response.getResult();
                if(result != null && result.size() > 0){
                    //处理京东订单
                    ordersAdd_byAppKey(result);
                    //本页有数据，则拉取下一页
                    pageNo = pageNo+1;
                    if(pageNo <= 50){//最大支持下载50页的数据
                        //递归请求下一页的数据
                        syncTimeOrder_byAppKey(elmOrderTimeVO, pageNo, client, downType);
                    }else{
                        return;
                    }
                }else{
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-----elm sync order err:--------",e);
        }
    }

    public void ordersAdd_byAppKey(List<AlibabaAlscUnionKbcpxPositiveOrderGetResponse.OrderDetailReportDTO> result) {
        int now = DateUtil.getNowTime();
        if (result==null || result.size() == 0){
            logger.info("-----elm order is null.-------");
            return ;
        }

        for (AlibabaAlscUnionKbcpxPositiveOrderGetResponse.OrderDetailReportDTO skuInfo:result){

            logger.info("----elmOrder----: bizOrderId: {}, parentOrderId: {}, orderState: {}, orderItemStatus: {}, income: {}, itemId: {}, productNum: {}, unitPrice: {}",
                        new Object[]{skuInfo.getBizOrderId(),skuInfo.getParentOrderId(), skuInfo.getOrderState(), skuInfo.getOrderItemStatus(),skuInfo.getIncome(), skuInfo.getItemId(),
                                skuInfo.getProductNum(), skuInfo.getUnitPrice()});

            //订单状态为空的不处理
            if(skuInfo.getOrderItemStatus() == null){
                continue;
            }

            //待付款不处理 order_item_status = 1 已下单
            if(skuInfo.getOrderItemStatus().intValue() == 1){
                continue;
            }

            //订单状态
            int bizStatus = bizStatus(skuInfo.getOrderItemStatus().intValue());

            // 根据订单号，商品id查询订单是否存在
            ElmOrders elmOrders = elmOrdersMapper.getByParAndCliId(String.valueOf(skuInfo.getParentOrderId()), String.valueOf(skuInfo.getBizOrderId()));
            if (elmOrders != null){

                //更新时间不一样或者订单状态不一样，就修改
                if((DateUtil.getStrTime(skuInfo.getGmtModified()) != elmOrders.getGmtModified().intValue())
                        || skuInfo.getOrderItemStatus().intValue() != elmOrders.getOrderItemStatus().intValue()){

                    logger.info("----elmOrder update :bizOrderId: {}, parentOrderId: {}, gmtModified: {}, orderItemStatus={}",
                            new Object[]{skuInfo.getBizOrderId(),skuInfo.getParentOrderId(), skuInfo.getGmtModified(), skuInfo.getOrderItemStatus()});

                    elmOrders.setTitle(skuInfo.getTitle());
                    elmOrders.setPicUrl(skuInfo.getPicUrl());
                    elmOrders.setShopName(skuInfo.getShopName());
                    elmOrders.setPayAmount(Math.currencyFormatToY(skuInfo.getPayAmount()));
                    elmOrders.setSettleAmount(Math.currencyFormatToY(skuInfo.getSettleAmount()));
                    elmOrders.setTraceTime(DateUtil.getStrTime(skuInfo.getTraceTime()));
                    elmOrders.setTkCreateTime(DateUtil.getStrTime(skuInfo.getTkCreateTime()));
                    elmOrders.setPayTime(DateUtil.getStrTime(skuInfo.getPayTime()));
                    elmOrders.setReceiveTime(DateUtil.getStrTime(skuInfo.getReceiveTime()));
                    elmOrders.setSettleTime(DateUtil.getStrTime(skuInfo.getSettleTime()));
                    elmOrders.setIncome(Math.currencyFormatToY(skuInfo.getIncome()));
                    elmOrders.setSettle(Math.currencyFormatToY(skuInfo.getSettle()));
                    elmOrders.setItemId(skuInfo.getItemId());
                    elmOrders.setProductNum(skuInfo.getProductNum() == null ? null: skuInfo.getProductNum().intValue());
                    elmOrders.setUnitPrice(Math.currencyFormatToY(skuInfo.getUnitPrice()));
                    elmOrders.setCategoryName(skuInfo.getCategoryName());
                    elmOrders.setBizOrderId(String.valueOf(skuInfo.getBizOrderId()));
                    elmOrders.setParentOrderId(String.valueOf(skuInfo.getParentOrderId()));
                    elmOrders.setMainItemId(skuInfo.getMainItemId());
                    elmOrders.setOrderState(skuInfo.getOrderState() == null ? null: skuInfo.getOrderState().intValue());
                    elmOrders.setOrderItemStatusName(skuInfo.getOrderItemStatusName());
                    elmOrders.setSettleState(skuInfo.getSettleState() == null ? null: skuInfo.getSettleState().intValue());
                    elmOrders.setFullSettleAmount(Math.currencyFormatToY(skuInfo.getFullSettleAmount()));
                    elmOrders.setCommissionRate(Math.currencyFormatToP(skuInfo.getCommissionRate()));
                    elmOrders.setCommissionFee(Math.currencyFormatToY(skuInfo.getCommissionFee()));
                    elmOrders.setSubsidyRate(Math.currencyFormatToP(skuInfo.getSubsidyRate()));
                    elmOrders.setSubsidyFee(Math.currencyFormatToY(skuInfo.getSubsidyFee()));
                    elmOrders.setIncomeRate(Math.currencyFormatToP(skuInfo.getIncomeRate()));
                    elmOrders.setStratifyRate(Math.currencyFormatToP(skuInfo.getStratifyRate()));
                    elmOrders.setDeductRate(Math.currencyFormatToP(skuInfo.getDeductRate()));
                    elmOrders.setPlatformCommissionRate(Math.currencyFormatToP(skuInfo.getPlatformCommissionRate()));
                    elmOrders.setPlatformCommissionFee(Math.currencyFormatToY(skuInfo.getPlatformCommissionFee()));
                    elmOrders.setChannelRate(Math.currencyFormatToP(skuInfo.getChannelRate()));
                    elmOrders.setChannelFee(Math.currencyFormatToY(skuInfo.getChannelFee()));
                    elmOrders.setMediaId(skuInfo.getMediaId());
                    elmOrders.setMediaName(skuInfo.getMediaName());
                    elmOrders.setAdZoneId(skuInfo.getAdZoneId());
                    elmOrders.setAdZoneName(skuInfo.getAdZoneName());
                    elmOrders.setActivityFee(Math.currencyFormatToY(skuInfo.getActivityFee()));
                    elmOrders.setActivityServiceFee(Math.currencyFormatToY(skuInfo.getActivityServiceFee()));
                    elmOrders.setActivityServiceRate(Math.currencyFormatToP(skuInfo.getActivityServiceRate()));
                    elmOrders.setGmtModified(DateUtil.getStrTime(skuInfo.getGmtModified()));
                    elmOrders.setTag(skuInfo.getTag());
                    elmOrders.setSid(skuInfo.getSid());
                    elmOrders.setPlatformType(skuInfo.getPlatformType()==null?null:skuInfo.getPlatformType().intValue());
                    elmOrders.setActivityId(String.valueOf(skuInfo.getActivityId()));
                    elmOrders.setUsedStoreId(skuInfo.getUsedStoreId());
                    elmOrders.setPid(skuInfo.getPid());
                    elmOrders.setRelationOrderId(String.valueOf(skuInfo.getRelationOrderId()));
                    elmOrders.setFlowType(skuInfo.getFlowType()==null?null:skuInfo.getFlowType().intValue());
                    elmOrders.setOrderItemStatus(skuInfo.getOrderItemStatus()==null?null:skuInfo.getOrderItemStatus().intValue());
                    elmOrders.setActivityInfoRemarkList(skuInfo.getActivityInfoRemarkList());
                    elmOrders.setChannelRightId(skuInfo.getChannelRightId());
                    elmOrders.setBizStatus(bizStatus);
                    elmOrders.setUpdateTime(now);
                    //修改订单
                    elmOrdersMapper.update(elmOrders);
                }
            }else {

                logger.info("----elmOrder add :bizOrderId: {}, parentOrderId: {}, gmtModified: {}, orderItemStatus={}",
                        new Object[]{skuInfo.getBizOrderId(),skuInfo.getParentOrderId(), skuInfo.getGmtModified(), skuInfo.getOrderItemStatus()});

                // 添加京东订单
                ElmOrders newElmOrder = new ElmOrders();
                newElmOrder.setId(IdWorker.getId());
                newElmOrder.setTitle(skuInfo.getTitle());
                newElmOrder.setPicUrl(skuInfo.getPicUrl());
                newElmOrder.setShopName(skuInfo.getShopName());
                newElmOrder.setPayAmount(Math.currencyFormatToY(skuInfo.getPayAmount()));
                newElmOrder.setSettleAmount(Math.currencyFormatToY(skuInfo.getSettleAmount()));
                newElmOrder.setTraceTime(DateUtil.getStrTime(skuInfo.getTraceTime()));
                newElmOrder.setTkCreateTime(DateUtil.getStrTime(skuInfo.getTkCreateTime()));
                newElmOrder.setPayTime(DateUtil.getStrTime(skuInfo.getPayTime()));
                newElmOrder.setReceiveTime(DateUtil.getStrTime(skuInfo.getReceiveTime()));
                newElmOrder.setSettleTime(DateUtil.getStrTime(skuInfo.getSettleTime()));
                newElmOrder.setIncome(Math.currencyFormatToY(skuInfo.getIncome()));
                newElmOrder.setSettle(Math.currencyFormatToY(skuInfo.getSettle()));
                newElmOrder.setItemId(skuInfo.getItemId());
                newElmOrder.setProductNum(skuInfo.getProductNum() == null ? null: skuInfo.getProductNum().intValue());
                newElmOrder.setUnitPrice(Math.currencyFormatToY(skuInfo.getUnitPrice()));
                newElmOrder.setCategoryName(skuInfo.getCategoryName());
                newElmOrder.setBizOrderId(String.valueOf(skuInfo.getBizOrderId()));
                newElmOrder.setParentOrderId(String.valueOf(skuInfo.getParentOrderId()));
                newElmOrder.setMainItemId(skuInfo.getMainItemId());
                newElmOrder.setOrderState(skuInfo.getOrderState() == null ? null: skuInfo.getOrderState().intValue());
                newElmOrder.setOrderItemStatusName(skuInfo.getOrderItemStatusName());
                newElmOrder.setSettleState(skuInfo.getSettleState() == null ? null: skuInfo.getSettleState().intValue());
                newElmOrder.setFullSettleAmount(Math.currencyFormatToY(skuInfo.getFullSettleAmount()));
                newElmOrder.setCommissionRate(Math.currencyFormatToP(skuInfo.getCommissionRate()));
                newElmOrder.setCommissionFee(Math.currencyFormatToY(skuInfo.getCommissionFee()));
                newElmOrder.setSubsidyRate(Math.currencyFormatToP(skuInfo.getSubsidyRate()));
                newElmOrder.setSubsidyFee(Math.currencyFormatToY(skuInfo.getSubsidyFee()));
                newElmOrder.setIncomeRate(Math.currencyFormatToP(skuInfo.getIncomeRate()));
                newElmOrder.setStratifyRate(Math.currencyFormatToP(skuInfo.getStratifyRate()));
                newElmOrder.setDeductRate(Math.currencyFormatToP(skuInfo.getDeductRate()));
                newElmOrder.setPlatformCommissionRate(Math.currencyFormatToP(skuInfo.getPlatformCommissionRate()));
                newElmOrder.setPlatformCommissionFee(Math.currencyFormatToY(skuInfo.getPlatformCommissionFee()));
                newElmOrder.setChannelRate(Math.currencyFormatToP(skuInfo.getChannelRate()));
                newElmOrder.setChannelFee(Math.currencyFormatToY(skuInfo.getChannelFee()));
                newElmOrder.setMediaId(skuInfo.getMediaId());
                newElmOrder.setMediaName(skuInfo.getMediaName());
                newElmOrder.setAdZoneId(skuInfo.getAdZoneId());
                newElmOrder.setAdZoneName(skuInfo.getAdZoneName());
                newElmOrder.setActivityFee(Math.currencyFormatToY(skuInfo.getActivityFee()));
                newElmOrder.setActivityServiceFee(Math.currencyFormatToY(skuInfo.getActivityServiceFee()));
                newElmOrder.setActivityServiceRate(Math.currencyFormatToP(skuInfo.getActivityServiceRate()));
                newElmOrder.setGmtModified(DateUtil.getStrTime(skuInfo.getGmtModified()));
                newElmOrder.setTag(skuInfo.getTag());
                newElmOrder.setSid(skuInfo.getSid());
                newElmOrder.setPlatformType(skuInfo.getPlatformType()==null?null:skuInfo.getPlatformType().intValue());
                newElmOrder.setActivityId(String.valueOf(skuInfo.getActivityId()));
                newElmOrder.setUsedStoreId(skuInfo.getUsedStoreId());
                newElmOrder.setPid(skuInfo.getPid());
                newElmOrder.setRelationOrderId(String.valueOf(skuInfo.getRelationOrderId()));
                newElmOrder.setFlowType(skuInfo.getFlowType()==null?null:skuInfo.getFlowType().intValue());
                newElmOrder.setOrderItemStatus(skuInfo.getOrderItemStatus()==null?null:skuInfo.getOrderItemStatus().intValue());
                newElmOrder.setActivityInfoRemarkList(skuInfo.getActivityInfoRemarkList());
                newElmOrder.setChannelRightId(skuInfo.getChannelRightId());
                newElmOrder.setBizStatus(bizStatus);
                newElmOrder.setUpdateTime(now);
                newElmOrder.setCreateTime(now);

                //保存订单
                elmOrdersMapper.add(newElmOrder);

            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncElmOrder_byAppKey_consumer(ElmOrderTimeVO emlOrderTimeVO, TaobaoClient client, Integer downType) {
        syncTimeOrder_byAppKey(emlOrderTimeVO,1, client, downType);
    }

}
